<template>
  <view class="banner-swiper">
    <swiper 
      class="swiper" 
      :indicator-dots="true" 
      :autoplay="true" 
      :interval="3000" 
      :duration="500"
      :circular="true"
      indicator-color="rgba(255, 255, 255, 0.6)"
      indicator-active-color="#ffffff"
    >
      <swiper-item v-for="banner in banners" :key="banner.id" @click="handleBannerClick(banner)">
        <image 
          :src="banner.imageUrl" 
          class="banner-image" 
          mode="aspectFill"
          @error="handleImageError"
        />
        <view class="banner-title" v-if="banner.title">{{ banner.title }}</view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { bannerApi } from '@/api/index.js';

// 响应式数据
const banners = ref([]);

// 加载轮播图数据
const loadBanners = async () => {
  try {
    const res = await bannerApi.getBanners();
    if (res.code === 200) {
      banners.value = res.data || [];
    }
  } catch (error) {
    console.error('加载轮播图失败:', error);
  }
};

// 处理轮播图点击
const handleBannerClick = (banner) => {
  if (!banner.linkType || banner.linkType === 'none') {
    return;
  }
  
  switch (banner.linkType) {
    case 'product':
      // 跳转到商品详情页
      uni.navigateTo({
        url: `/pages/product/detail?id=${banner.linkId}`
      });
      break;
    case 'category':
      // 跳转到分类页面
      uni.navigateTo({
        url: `/pages/category/list?id=${banner.linkId}`
      });
      break;
    case 'url':
      // 跳转到外部链接
      if (banner.linkUrl) {
        // #ifdef H5
        window.open(banner.linkUrl);
        // #endif
        // #ifdef MP-WEIXIN
        uni.navigateTo({
          url: `/pages/webview/index?url=${encodeURIComponent(banner.linkUrl)}`
        });
        // #endif
      }
      break;
  }
};

// 处理图片加载错误
const handleImageError = () => {
  console.warn('轮播图图片加载失败');
};

onShow(() => {
  loadBanners();
});

// // 生命周期
// onMounted(() => {
//   loadBanners();
// });
</script>

<style scoped>
.banner-swiper {
  width: 100%;
  height: 300rpx;
  margin-bottom: 20rpx;
}

.swiper {
  width: 100%;
  height: 100%;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.banner-title {
  position: absolute;
  bottom: 20rpx;
  left: 20rpx;
  right: 20rpx;
  color: #ffffff;
  font-size: 28rpx;
  font-weight: bold;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.3));
  padding: 20rpx;
  border-radius: 0 0 10rpx 10rpx;
}
</style> 